package yt.kpool.activity.setting;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import yt.kpool.R;
import yt.kpool.activity.personal.FastLookActivity;
import yt.kpool.adapter.FastLookListAdapter;
import yt.kpool.base.BaseApplication;
import yt.kpool.bean.FastLookAccountBean;
import yt.kpool.bean.KeyLoginBean;
import yt.kpool.network.HttpUtils;
import yt.kpool.network.MyGson;
import yt.kpool.network.NetHelperNew;
import yt.kpool.util.NetWorkUtil;
import yt.kpool.util.SPUtil;
import yt.kpool.util.TitleControl;
import yt.kpool.util.ToastUtil;
import yt.kpool.view.dialog.LoadingDialog;

/**
 * 快速查看列表页
 */
public class FastLookListActivity extends AppCompatActivity {

    @BindView(R.id.listview)
    ListView listview;

    private List<FastLookAccountBean> fastLookAccountBeans;
    private FastLookListAdapter fastLookListAdapter;
    private SQLiteDatabase db;
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fast_look_list);
        ButterKnife.bind(this);
        initTitle();
        initDb();
    }

    /**
     * 快速查看账户数据库
     */
    private void initDb() {
        db = Connector.getDatabase();
        fastLookAccountBeans = new ArrayList<>();

        fastLookListAdapter = new FastLookListAdapter(this, fastLookAccountBeans);
        listview.setAdapter(fastLookListAdapter);

        getData();


        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                if (i != fastLookListAdapter.getSelectPos()) {


                    String link = fastLookAccountBeans.get(i).getLink();
                    if ("".equals(link)) {
                        ToastUtil.showToast(FastLookListActivity.this, "链接为空");

                    } else {
                        int j = link.indexOf("=");
                        if (j == -1) {
                            fastLogin(link);
                        } else {
                            if (link.length() > j + 1)
                                fastLogin(link.substring(j + 1));
                        }

                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        fastLookAccountBeans.clear();
        fastLookListAdapter.notifyDataSetChanged();
        fastLookAccountBeans.addAll(DataSupport.select("remark", "accountId", "name", "link").order("id desc").find(FastLookAccountBean.class));

        SPUtil spUtil = new SPUtil(this, BaseApplication.KEYLOGIN);
        String name = spUtil.getString(BaseApplication.ChildAccountName, "");
        int pos = -1;
        for (int i = 0; i < fastLookAccountBeans.size(); i++) {
            if (name.equals(fastLookAccountBeans.get(i).getName())) {
                pos = i;
            }
        }
        fastLookListAdapter.setSelectPos(pos);

        fastLookListAdapter.notifyDataSetChanged();
    }

    /**
     * 快速登录
     *
     * @param key
     */
    private void fastLogin(String key) {
        if (NetWorkUtil.check(this)) {


            loadingDialog.show();
            NetHelperNew.KeyLogin(key, new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    loadingDialog.dismiss();
                    Log.i("-->", "快速查看返回结果：" + data);
                    KeyLoginBean keyLoginBean = MyGson.getInstance().fromJson(data, KeyLoginBean.class);
                    if (keyLoginBean.getType() == 1) {

                        SPUtil spUtil = new SPUtil(BaseApplication.context, BaseApplication.KEYLOGIN);

                        spUtil.putString(BaseApplication.NAME, keyLoginBean.getData().getLoginModel().getUserName());
                        spUtil.putString(BaseApplication.ID, keyLoginBean.getData().getLoginModel().getUserID() + "");
                        spUtil.putString(BaseApplication.ChildAccountId, keyLoginBean.getData().getChildAccount().getChildAccountId() + "");
                        spUtil.putString(BaseApplication.ChildAccountName, keyLoginBean.getData().getChildAccount().getChildAccountName());
                        setResult(66, getIntent());
                        finish();

                    } else {
                        ToastUtil.showToast(getApplicationContext(), keyLoginBean.getContent());
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);

                    loadingDialog.dismiss();
                    ToastUtil.showToast(getApplicationContext(), msg);
                }
            });


        }

    }

    private void initTitle() {
        TitleControl titleControl = new TitleControl(this);
        titleControl.setTitle("全部链接");
        titleControl.setRightImg(R.mipmap.jiahao, new TitleControl.OnClickRight() {
            @Override
            public void onRight() {

                startActivityForResult(new Intent(FastLookListActivity.this, FastLookActivity.class), 15);

            }
        });
        loadingDialog = new LoadingDialog(this, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 66) {
            setResult(66, getIntent());
            finish();
        }
    }
}
